﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.OleDb;
/// <summary>
/// Summary description for WebFunction
/// </summary>
public class WebFunction
{
    // Random number
    private int GetRandomNum(int minValue, int maxValue)
    {
        Random rand = new Random();
        return rand.Next(minValue, maxValue + 1);
    }

    // Convert DateTime dd/MM/yyyy to MM/dd/yyyy.
    public DateTime Convert_ddMMyyyy_MMddyyyy(string datein)
    {
        DateTime date = DateTime.ParseExact(datein, new string[] { "dd/MM/yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces);
        string dateformat = string.Format("{0: MM/dd/yyyy}", date);
        DateTime dateout = DateTime.Parse(dateformat);
        return dateout;
    }

    // Format numeic VietNam.
    public string FormatNumber(int num)
    {
        string format = String.Format("{0:0,0}", num);
        string result = format.Replace(".", ",");
        if (result == "00")
            result = "0";
        return result;
    }

    // Format numeric VietNam in list Data.
    public static string FormatNumberList(object num)
    {
        if (num == null || num.ToString() == "")
            return null;
        else
        {
            int number = Int32.Parse(num.ToString());
            string format = String.Format("{0:0,0}", number);
            string result = format.Replace(".", ",");
            if (result == "00")
                result = "0";
            return result;
        }
    }

    // Format numeric VietNam style Double in list Data.
    public static string FormatNumberDoubleList(object num)
    {
        if (num == null || num.ToString() == "")
            return null;
        else
        {
            Decimal number = System.Decimal.Round(Convert.ToDecimal(num.ToString()));
            string format = String.Format("{0:0,0}", number);
            string result = format.Replace(".", ",");
            if (result == "00")
                result = "0";
            return result;
        }
    }

    // Format Datetime to dd/MM/yyyy.
    public string FormatDate(DateTime date)
    {
        string result = date.ToString("dd/MM/yyyy");
        return result;
    }


    // Format Datetime to MM/dd/yyyy.
    public string FormatDateMMDDYY(DateTime date)
    {
        string result = date.ToString("MM/dd/yyyy");
        return result;
    }

    // Format Datetime to dd/MM/yyyy in list Data.
    public static string FormatDateList(object date)
    {
        if (date == null || date.ToString() == "")
            return null;
        else
        {
            DateTime date_af = DateTime.Parse(date.ToString());
            string result = date_af.ToString("dd/MM/yyyy");
            return result;
        }
    }

    // Format Datetime to dd/MM/yyyy.
    public string FormatDateToTime(DateTime date)
    {
        string result = date.ToLongTimeString();
        return result;
    }

    // Format Datetime to dd/MM/yyyy in list Data.
    public static string FormatDateToTime_List(object date)
    {
        if (date == null || date.ToString() == "")
            return null;
        else
        {
            DateTime date_af = DateTime.Parse(date.ToString());
            string result = date_af.ToLongTimeString();
            return result;
        }
    }

    // Format Gender.
    public string FormatGender(string num)
    {
        string gender = "Nữ";
        if (num == "1")
            gender = "Nam";
        return gender;
    }

    // Format Gender in list Data.
    public static string FormatGender(object gender)
    {
        if (gender == null || gender.ToString() == "")
            return null;
        else
        {
            string result = "";
            string temp = gender.ToString();
            if (temp == "1")
                result = "Nam";
            else
                result = "Nữ";
            return result;
        }
    }

    // Load Data to Dropdownlist
    public void LoadDataToDropDownList(DropDownList ddl, DataTable ds, string value, string text, bool Empty)
    {
        if (ds.Rows.Count > 0)
        {
            ddl.DataSource = ds;
            ddl.DataValueField = value;
            ddl.DataTextField = text;
            ddl.DataBind();
        }

        if (Empty == true)
        {
            ListItem list = new ListItem();
            list.Text = "Choose";
            list.Value = String.Empty;
            ddl.Items.Insert(0, list);
        }
    }

    // Encrypt MD5.
    public string HashMD5(string str)
    {
        UTF32Encoding utf = new UTF32Encoding();
        byte[] bytes = utf.GetBytes(str);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(bytes);
        return Convert.ToBase64String(result);
    }

    // Return URL.
    public string ReturnURL(string temp)
    {
        string[] word = temp.Split('/');
        int i = word.Length;
        return word[i - 1].ToString();
    }

    public string escapeURL(string text)
    {
        string result = "";
        result = text.Trim();
        result = text.Replace(" ", "-");
        return result;
    }

    public string descapeURL(string text)
    {
        string result = "";
        result = text.Trim();
        result = text.Replace("-", " ");
        return result;
    }

    public string ConvertToUnSign(string text)
    {
        for (int i = 32; i < 48; i++)
        {
            text = text.Replace(((char)i).ToString(), " ");
        }

        for (int j = 0; j < 2; j++)
        {
            text = text.Replace(" ", "-");
            text = text.Replace(",", "");
            text = text.Replace(";", "");
            text = text.Replace(":", "");
            text = text.Replace("”", "");
            text = text.Replace("“", "");
            text = text.Replace("?", "");
            text = text.Replace("/", "-");
            text = text.Replace("....", "");
            text = text.Replace("...", "");
            text = text.Replace("..", "");
            text = text.Replace(".", "");
            text = text.Replace("-----", "-");
            text = text.Replace("----", "-");
            text = text.Replace("---", "-");
            text = text.Replace("--", "-");
        }

        Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
        string strFormD = text.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
    }

    // Format Status
    public string FormatStatus(string status)
    {
        string result = "";
        if (status == "1")
            result = "NORMAL";
        else
            result = "STANDBY";
        return result;
    }

    // Format Status in list Data.
    public static string FormatStatusList(object status)
    {
        if (status == null || status.ToString() == "")
            return null;
        else
        {
            string result = "";
            string temp = status.ToString();
            if (temp == "1")
                result = "NORMAL";
            else
                result = "STANDBY";
            return result;
        }
    }

    // Encrypt Keyword
    public static string EncryptKeyWord(string toEncrypt, string key, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    // Decrypt Keyword
    public static string DecryptKeyWord(string toDecrypt, string key, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    // Resize Image
    public string resizeImage(HttpPostedFile uploadFile, string path, string filename, int widthimg, int heightimg)
    {
        try
        {
            int thumbWidth = widthimg;
            int thumbHeight = heightimg;
            System.Drawing.Image oImg = System.Drawing.Image.FromStream(uploadFile.InputStream);
            System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
            Graphics oGraphic = Graphics.FromImage(oThumbNail);
            oGraphic.CompositingQuality = CompositingQuality.HighQuality;
            oGraphic.SmoothingMode = SmoothingMode.HighQuality;
            oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
            oGraphic.DrawImage(oImg, -1, -1, widthimg + 1, heightimg + 1);//(oImg, oRectangle);
            oThumbNail.Save(path + filename + ".jpg", ImageFormat.Jpeg);
            oImg.Dispose();
            return filename + ".jpg";
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public int IsNullConvertInt32(string input, int num)
    {
        int result = 0;
        if (input == "" || input == null)
            result = num;
        else
            result = Convert.ToInt32(input);
        return result;
    }

    public string IsNullConvertIString(string input)
    {
        string result = "";
        if (input == "" || input == null)
            result = null;
        else
            result = input;
        return result;
    }

    public DataTable ReadDaTableFromExcel(string fileExtension, string fileLocation)
    {
        string connectionString = "";

        //Check whether file extension is xls or xslx
        if (fileExtension == ".xls")
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        else if (fileExtension == ".xlsx")
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";

        OleDbConnection con = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
        con.Open();
        DataTable dtExcelRecords = new DataTable();
        DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
        cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
        dAdapter.SelectCommand = cmd;
        dAdapter.Fill(dtExcelRecords);
        con.Close();

        return dtExcelRecords;
    }

    // Get String Day and Hour
    public string getStringDayAndHour()
    {
        string result = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
        return result;
    }

    // Replace Extension
    public string replaceExtension(string str)
    {
        if(str != null && str != "")
            str = str.Replace("~/", "");
        return str;
    }

    // Add Extension
    public string addExtension(string str)
    {
        if (str != null && str != "")
            str = "~/" + str;
        return str;
    }

    public string FormatLength(string str, int num)
    {
        int length = str.Length;
        if (length > num)
            str = str.Substring(0, num) + "...";
        return str;
    }

    // Format Status in list Data.
    public static string FormatLengthList(object str, int num)
    {
        if (str == null || str.ToString() == "")
            return null;
        else
        {
            int length = str.ToString().Length;
            if (length > num)
                str = str.ToString().Substring(0, num) + "...";
            return str.ToString();
        }
    }

    // Replace & XML
    public string replacexmlin(string str)
    {
        if(str != "")
            str = str.Replace("&", "tempand");
        return str;
    }

    // Replace & XML
    public static string replacexmlout(object str)
    {
        if (str == null || str.ToString() == "")
            str = "";
        else
            str = str.ToString().Replace("tempand", "&");

        return str.ToString();
    }

    // Replace ,
    public string numRemove(string str)
    {
        if (str != "")
        {
            for (int i = 0; i < 3; i++ )
                str = str.Replace(",", "");
        }
        return str;
    }
}